import React, { useRef, useEffect, useState } from 'react';
import { useFrame, useThree } from '@react-three/fiber';
import { PerspectiveCamera } from '@react-three/drei';
import * as THREE from 'three';

interface PlayerProps {
  initialPosition: [number, number, number];
  moveSpeed?: number;
  mouseSensitivity?: number;







  isActive?: boolean;
  roomSize?: number
}

const ThreeDCom: React.FC<PlayerProps> = ({
  initialPosition,
  moveSpeed = 0.1,
  mouseSensitivity = 0.002,
  isActive = false,
  roomSize = 80
}) => {
  const playerRef = useRef<THREE.Group>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera>(null);
  const { scene } = useThree();
  const raycaster = useRef(new THREE.Raycaster());

  // 玩家参数
  const playerHeight = 1.7;
  const eyeHeight = 1.6;
  const playerRadius = 0.3;
  const jumpForce = 0.15;
  const gravity = 0.005;

  // 运动状态
  const [cameraRotation, setCameraRotation] = useState({ x: 0, y: 0 });
  const [playerRotation, setPlayerRotation] = useState(0);
  const velocity = useRef(new THREE.Vector3());
  const canJump = useRef(true);

  const moveState = useRef({
    forward: false,
    backward: false,
    left: false,
    right: false
  });

  // 检测地面
  const checkGroundCollision = () => {
    if (!playerRef.current) return false;

    const start = new THREE.Vector3(
      playerRef.current.position.x,
      playerRef.current.position.y - playerHeight / 2 + 0.1,
      playerRef.current.position.z
    );
    raycaster.current.set(start, new THREE.Vector3(0, -1, 0));

    const intersects = raycaster.current.intersectObjects(scene.children);
    return intersects.length > 0 && intersects[0].distance < 0.2;
  };

  // 键盘控制
  useEffect(() => {
    if (!isActive) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      switch (e.code) {
        case 'KeyW': moveState.current.forward = true; break;
        case 'KeyS': moveState.current.backward = true; break;
        case 'KeyA': moveState.current.left = true; break;
        case 'KeyD': moveState.current.right = true; break;
        case 'Space':
          if (canJump.current) {
            velocity.current.y = jumpForce;
            canJump.current = false;
          }
          break;
      }
    };

    const handleKeyUp = (e: KeyboardEvent) => {
      switch (e.code) {
        case 'KeyW': moveState.current.forward = false; break;
        case 'KeyS': moveState.current.backward = false; break;
        case 'KeyA': moveState.current.left = false; break;
        case 'KeyD': moveState.current.right = false; break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, [isActive]);

  // 鼠标控制
  useEffect(() => {
    if (!isActive) return;

    const handleMouseMove = (e: MouseEvent) => {
      if (document.pointerLockElement) {
        setCameraRotation(prev => ({
          x: THREE.MathUtils.clamp(
            prev.x - e.movementY * mouseSensitivity,
            -Math.PI / 2,
            Math.PI / 2
          ),
          y: prev.y
        }));
        setPlayerRotation(prev => prev - e.movementX * mouseSensitivity);
      }
    };

    document.addEventListener('mousemove', handleMouseMove);
    return () => document.removeEventListener('mousemove', handleMouseMove);
  }, [mouseSensitivity, isActive]);

  // 每帧更新
  useFrame(() => {
    if (!playerRef.current || !cameraRef.current || !isActive) return;

    // 更新旋转
    playerRef.current.rotation.y = playerRotation;
    cameraRef.current.rotation.x = cameraRotation.x;



    // 处理水平移动
    const direction = new THREE.Vector3();
    const rotation = playerRef.current.rotation.y;

    if (moveState.current.forward) direction.z -= 1;
    if (moveState.current.backward) direction.z += 1;
    if (moveState.current.left) direction.x -= 1;
    if (moveState.current.right) direction.x += 1;

    direction.normalize();
    direction.applyAxisAngle(new THREE.Vector3(0, 1, 0), rotation);

    // 应用水平速度
    velocity.current.x = direction.x * moveSpeed;
    velocity.current.z = direction.z * moveSpeed;

    // 应用重力
    velocity.current.y -= gravity;

    // 检测地面
    const onGround = checkGroundCollision();
    if (onGround) {
      velocity.current.y = Math.max(velocity.current.y, 0);
      canJump.current = true;
    }

    // 碰撞检测
    const newPosition = playerRef.current.position
      .clone()
      .add(velocity.current);

    // 边界限制
    newPosition.x = THREE.MathUtils.clamp(newPosition.x, -roomSize, roomSize);
    newPosition.z = THREE.MathUtils.clamp(newPosition.z, -roomSize, roomSize);
    newPosition.y = THREE.MathUtils.clamp(newPosition.y, 0.1, 14);

    playerRef.current.position.copy(newPosition);
  });

  // 初始化相机
  useEffect(() => {
    if (cameraRef.current) {
      cameraRef.current.position.y = eyeHeight;
    }
  }, []);

  return (
    <group ref={playerRef} position={initialPosition}>
      <PerspectiveCamera makeDefault ref={cameraRef} fov={75} />
    </group>
  );
};

export default ThreeDCom;
